package com.xyw.code.platform.webapps.service.impl;

import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyw.code.common.core.constant.IsDelEnum;
import com.xyw.code.common.core.entity.vo.SecurityUser;
import com.xyw.code.common.core.exception.BaseException;
import com.xyw.code.common.core.util.UserContextHolder;
import com.xyw.code.platform.common.entity.dto.UserDTO;
import com.xyw.code.platform.common.entity.dto.UserInfoDTO;
import com.xyw.code.platform.common.entity.enums.OssFileConstant;
import com.xyw.code.platform.common.entity.enums.PlatformErrorType;
import com.xyw.code.platform.common.entity.po.SysUser;
import com.xyw.code.platform.common.entity.po.SysUserRole;
import com.xyw.code.platform.common.entity.util.XUtil;
import com.xyw.code.platform.webapps.config.DataScope;
import com.xyw.code.platform.webapps.dao.SysUserMapper;
import com.xyw.code.platform.webapps.service.ISysDeptService;
import com.xyw.code.platform.webapps.service.ISysUserRoleService;
import com.xyw.code.platform.webapps.service.ISysUserService;
import com.xyw.code.platform.webapps.util.AliyunOSSUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 用户表 服务实现类
 * </p>
 *
 * @author xyw
 * @since 2020-02-07
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private ISysDeptService deptService;

    @Autowired
    private ISysUserRoleService userRoleService;

    @Override
    public IPage<SysUser> getUsersWithRolePage(UserDTO userDTO) {
        Page page = new Page(userDTO.getPage(),userDTO.getPageSize());
        if (ObjectUtil.isNotNull(userDTO) && !"0".equals(userDTO.getDeptId())){
            userDTO.setDeptList(deptService.selectDeptIds(userDTO.getDeptId()));
        }
        return baseMapper.getUserVosPage(page, userDTO, new DataScope());
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean insertUser(UserDTO userDto) {
        if (checkPhone(userDto.getPhone(), null)) {
            throw new BaseException(PlatformErrorType.PHONE_REPEAT);
        }
        SysUser sysUser = new SysUser();

        BeanUtils.copyProperties(userDto, sysUser);
        // 默认密码 123456
        sysUser.setPassword(XUtil.encode("123456"));
        baseMapper.insert(sysUser);
        List<SysUserRole> userRoles = userDto.getRoleList().stream().map(item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(item);
            sysUserRole.setUserId(sysUser.getId());
            return sysUserRole;
        }).collect(Collectors.toList());
        return userRoleService.saveBatch(userRoles);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateUser(UserDTO userDto) {
        if (checkPhone(userDto.getPhone(), userDto.getId())) {
            throw new BaseException(PlatformErrorType.PHONE_REPEAT);
        }
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(userDto, sysUser);
        baseMapper.updateById(sysUser);
        userRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, sysUser.getId()));
        List<SysUserRole> userRoles = userDto.getRoleList().stream().map(item -> {
            SysUserRole sysUserRole = new SysUserRole();
            sysUserRole.setRoleId(item);
            sysUserRole.setUserId(sysUser.getId());
            return sysUserRole;
        }).collect(Collectors.toList());
        return userRoleService.saveBatch(userRoles);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean removeUser(String userId) {
        SysUser sysUser = new SysUser();
        sysUser.setId(userId);
        sysUser.setDelFlag(IsDelEnum.DEL.getKey());
        baseMapper.updateById(sysUser);
        return userRoleService.remove(Wrappers.<SysUserRole>lambdaQuery().eq(SysUserRole::getUserId, userId));
    }

    @Override
    public boolean restPass(String userId) {
        SysUser user = new SysUser();
        user.setPassword(new BCryptPasswordEncoder().encode("123456"));
        user.setId(userId);
        return baseMapper.updateById(user) > 0;
    }

    @Override
    public String uploadAvatar(MultipartFile file) {
        return AliyunOSSUtil.upLoad(file, OssFileConstant.avatar);
    }

    @Override
    public Boolean updateUserInfo(UserInfoDTO userDto) {
        SecurityUser user = UserContextHolder.getInstance().getContext();
        SysUser sysUser = new SysUser();
        sysUser.setId(user.getUserId());
        BeanUtils.copyProperties(userDto,sysUser);
        return updateById(sysUser);
    }

    @Override
    public Boolean updatePass(String oldPass, String newPass) {
        //先验证老密码对不对
        SysUser user = this.lambdaQuery().eq(SysUser::getUsername,UserContextHolder.getInstance().getUsername())
                .eq(SysUser::getDelFlag,IsDelEnum.USE).one();
        if(!XUtil.validatePass(oldPass,user.getPassword())){
            throw new BaseException(PlatformErrorType.ORIGINAL_PASSWORD_ERROR);
        }
        if(oldPass.equals(newPass)){
            throw new BaseException(PlatformErrorType.PASSWORD_SAME);
        }

        String newPassEncode = XUtil.encode(newPass);
        user.setPassword(newPassEncode);
        return updateById(user);
    }

    @Override
    public Boolean updateEmail(String email, String code,String sessionCode) {
        if(StringUtils.isEmpty(code)){
            throw new BaseException(PlatformErrorType.VERIFICATION_CODE_NULL);
        }
        if(StringUtils.isEmpty(sessionCode)){
            throw new BaseException(PlatformErrorType.VERIFICATION_CODE_INVALID);
        }
        if(!code.toLowerCase().equals(sessionCode.toLowerCase())){
            throw new BaseException(PlatformErrorType.VERIFICATION_CODE_ERROR);
        }
        SysUser sysUser = this.lambdaQuery().eq(SysUser::getUsername,UserContextHolder.getInstance().getUsername())
                .eq(SysUser::getDelFlag,IsDelEnum.USE).one();
        sysUser.setEmail(email);
        return updateById(sysUser);
    }

    /**
     * 判断手机号码是不是重复  如果重复 返回true 如果不重复返回false
     * @param phone
     * @param userId
     * @return
     */
    public boolean checkPhone(String phone,String userId){
        LambdaQueryWrapper<SysUser> wrappers = Wrappers.<SysUser>lambdaQuery();
        wrappers.eq(SysUser::getPhone,phone);
        if(userId!=null){
            wrappers.ne(SysUser::getId,userId);
        }
        List<SysUser> list = baseMapper.selectList(wrappers);
        if(list.size()>0){
            return true;
        }
        return false;
    }
}
